package api

import (
	. "com.mgface.disobj/common"
	"encoding/json"
	"fmt"
	log "github.com/sirupsen/logrus"
	"math/rand"
	"net"
	"sync"
	"time"
)

//全局数据节点map集合，key为节点的addr，value是节点的更新时间
var dataNodes = make(map[string]string)
var mutex sync.Mutex
var mnAddr string

//刷新datanodes的数据
func RefreshDNData(metanodeAddr string) {
	mnAddr = metanodeAddr //把MQ的地址写入通道
	client := NewReconTCPClient(metanodeAddr)
	cmd := &Cmd{Name: "get", Key: "dataNodes", Value: ""}
	//是否需要读取缓存的数据
	enabledCached := false

	for {
	reconn:
		if enabledCached {
			//重连
			log.Debug(fmt.Sprintf("[更新内存数据服务]等待重连元数据服务端[%s]...", metanodeAddr))
			client = NewReconTCPClient(metanodeAddr)
			if client != nil {
				enabledCached = false
				goto reconn
			}
		} else {
			//执行命令，获取dataNodes数据
			//值置空
			cmd.Value = ""
			cmd.Run(client)

			//判断执行的错误异常
			if cmd.Error != nil {
				//log.Debug(cmd.Error.Error())
				t, ok := cmd.Error.(*net.OpError)
				if ok {
					if t.Op == "write" {
						//如果还是连接不上元服务器端，那么直接取缓存的数据
						enabledCached = true
					}
				}
			}
		}
		if enabledCached {
			data, _ := json.MarshalIndent(dataNodes["dataNodes"], "", "\t")
			fmt.Println("[更新内存数据服务]获取【缓存】服务节点信息:", string(data))
		} else {
			data, _ := json.MarshalIndent(cmd, "", "\t")
			fmt.Println("[更新内存数据服务]获取【实时】服务节点信息:", string(data))
			mutex.Lock()
			dataNodes["dataNodes"] = cmd.Value
			mutex.Unlock()
		}
		time.Sleep(time.Duration(5+rand.Intn(5)) * time.Second)
	}
}
